# -*- coding: utf-8 -*-
# @Time    : 2024/11/18 11:24
# @Author  : wangwei
# @File    : json_util.py

import jsonpath
from jsonpath_rw import Index, Fields
from jsonpath_rw_ext import parse

from common.logger import GetLogger


def update_value_to_json(json_object, json_path, new_value):
    json_path_expr = parse(json_path) # $.goods_name
    # print(json_path_expr)
    for match in json_path_expr.find(json_object):
        # print(match)
        path = match.path
        print(path)
        if isinstance(path, Index):
            match.context.value[match.path.index] = new_value
        elif isinstance(path, Fields):
            match.context.value[match.path.fields[0]] = new_value
    return json_object

def extract_json(json_object,json_path,index=0):
    res = jsonpath.jsonpath(json_object,json_path)
    # 匹配到的res有可能是False，有可能是列表
    GetLogger.logger.info(f'从{json_object}中通过【{json_path}】提取到的结果是:【{res}】')
    if res:
        # 如果index小于0，说明你要的是匹配到的全部结果，直接返回res
        if index<0:
            return res
        else:
            return res[index]
    else:
        return res

if __name__ == '__main__':
    json_data = {
        "goods_name":"商品名称",
        "price":300,
        "info":[
            {
                "aaa":"aaa",
                "bbb":"bbb"
            },
            {
                "aaa": "aaa1",
                "bbb": "bbb1"
            }
        ]
    }
    parmas = {
        "$.goods_name":"修改后的商品名称",
        "$.info[0].aaa":"new aaa"

    }
    # new_json_data = update_value_to_json(json_data,"$.goods_name","修改后的商品名称")
    # print(new_json_data)
    # new_json_data = update_value_to_json(new_json_data, "$.info[0].aaa", "new aaa")
    # print(new_json_data)
    # for json_path,new_value in parmas.items():
    #     json_data = update_value_to_json(json_data, json_path, new_value)
    # print(json_data)

    # 数据提取调试
    # 从json_data中提取price字段的值
    res = jsonpath.jsonpath(json_data,"$.price")
    print(res)
    # 从json_data中提取aaa字段的值
    res = jsonpath.jsonpath(json_data,"$..aaa")
    print(res)
    # 如果jsonpath匹配不到任何结果，那么返回值就是一个Fasle
    res = jsonpath.jsonpath(json_data,"$..aaa1")
    print(res)

    print(extract_json(json_data, "$.price"))
    print(extract_json(json_data, "$..aaa",index=1))
    print(extract_json(json_data, "$..aaa", index=-1))